
* cutoff=-0.35 and cutoff=-0.45 also gives similar results
*cutoff for shock
local cutoff -0.4
*cutoff for previous years
local cutoff2 -0.3

use "$singleaudit\singleaudit_cfda", clear
joinby cfda using "$data/matching/cfda_proportion"

*drop years non-overlapping with IRIS data
drop if year<minyear
drop if year>maxyear
egen cfda_num = group(cfda)
tsset cfda_num year
gen logrd=log(amount_rd)
gen d_logrd=log(amount_rd)-log(L.amount_rd)
by cfda_num: egen mostnegativeshock=min(d_logrd)

*drop CFDA codes with less than 5 years after 2010
by cfda_num: egen number_year=sum(year>=2010)
drop if number_year<=5

*define negative shock
gen byte temp_neg_shock= (d_logrd<`cutoff')

*require shock to be temporary
gen futuremax=log(F.amount_rd)
forv i=2/10 {
replace futuremax=log(F`i'.amount_rd) if log(F`i'.amount_rd)>futuremax & log(F`i'.amount_rd)<.
}
gen diff=futuremax-log(L.amount_rd)
replace temp_neg_shock=0 if diff<0 | diff==.

*require no large positive or negative shocks right before the shock
replace temp_neg_shock=0 if L.d_logrd>-`cutoff2' | (L2.d_logrd>-`cutoff2' & L2.d_logrd<.)
replace temp_neg_shock=0 if L.d_logrd<`cutoff2' | L2.d_logrd<`cutoff2'

gen temp_year=year if temp_neg_shock==1
by cfda_num: egen year_shock=min(temp_year)
by cfda_num: egen nshock=sum(temp_neg_shock)

*plot funding overtime (Figure 2)
gen tau=year-year_shock
forv i=6(-1)1 {
    gen taum`i'=(tau==-`i')
}
forv i=1/6 {
    gen tau`i'=(tau==`i')
}
eststo: reghdfe logrd taum6-tau6 if nshock==1 & tau^2<=36, absorb(cfda_num)
reghdfe logrd taum5-tau5 if nshock==1 & tau^2<=25 [aw=total_proportion], absorb(cfda_num)

drop if mostnegativeshock<`cutoff2' & nshock==0

collapse nshock year_shock*, by (cfda)
compress
save "$data/matching/cfda_shocks", replace


*construct treatment and control group
use "$data/matching/employee_cfda", clear
*treatment group: people getting >50% of funding from a treated CFDA 
merge m:1 cfda using "$data/matching/cfda_shocks", keep(3)
gen share_treatment=proportion if nshock>0
bysort iris: egen maxshare_treatment=max(share_treatment)
drop if share_treatment!=.&share_treatment!=maxshare_treatment
gen share_control=proportion if nshock==0
collapse (sum) share_treatment share_control (mean) year_shock* minyear maxyear (max) nshock, by(iris)
count if share_control>=0.5 & share_treatment==0
count if share_treatment>=0.5 & year_shock>minyear
*require shock is after the first year of funding
gen treated=1 if share_treatment>0.5 & year_shock>minyear
replace treated=0 if share_control>=0.5 & share_treatment==0
drop if treated==.
keep iris treated year_shock minyear
compress
save "$data/matching/employee_shocks", replace
